//
//  ViewController.swift
//  Notifi
//
//  Created by Wei Zhou on 2017/8/17.
//  Copyright © 2017年 Wulian. All rights reserved.
//

import UIKit
import UserNotifications
import CoreBluetooth
import os.log

class ViewController: UIViewController ,CBCentralManagerDelegate, CBPeripheralManagerDelegate, CBPeripheralDelegate, UITableViewDelegate, UITableViewDataSource {
   
    @IBOutlet weak var tableview: UITableView!
    @IBOutlet weak var textview: UITextView!
    
    var cenMG : CBCentralManager? = nil
    var peripherallist = [CBPeripheral]()
    var curPeripheral : CBPeripheral? = nil
//    var fmg : FileManager? {
//        didSet{
//            let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
//            let file = path+"/log.txt"
//            if let fmg = fmg {
//                if !fmg.fileExists(atPath: file) {
//                    fmg.createFile(atPath: file, contents: nil, attributes: nil)
//                }
//            }
//        }
//    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableview.tableFooterView = UIView()
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (success, error) in
            if success {
                UIApplication.shared.registerForRemoteNotifications()
            } else {
                if let error = error {
                    let alert = UIAlertController.init(title: "hehe", message: error.localizedDescription, preferredStyle: .alert)
                    alert.show(self, sender: nil)
                }
            }
        }
//        fmg = FileManager.default
        cenMG = CBCentralManager(delegate: self, queue: nil)
    }
    
    @IBAction func bluetoothClick(_ sender: UIButton) {
        self.textview.text = nil
//        let uuid = CBUUID.init(string: "6814") //特殊服务
//        let uuid = CBUUID.init(string: "7E841885-F9AD-4D12-A38C-5BB870FFCE83") //设备
//        let batteryUuid = CBUUID.init(string: "180F") //电池服务
        
        
        self.cenMG?.scanForPeripherals(withServices: nil, options: nil)
        
//        self.cenMG?.scanForPeripherals(withServices: [uuid], options: [CBCentralManagerScanOptionAllowDuplicatesKey:true])
//        self.cenMG?.scanForPeripherals(withServices: [batteryUuid], options: [CBCentralManagerScanOptionSolicitedServiceUUIDsKey:[batteryUuid]])
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: - CBCentralManagerDelegate && CBPeripheralManagerDelegate
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .unknown:
            print("Bluetooth Unknown")
        case .unauthorized:
            print("Bluetooth unauthorized")
        case .poweredOff:
            print("Bluetooth poweredOff")
        case .poweredOn:
            print("Bluetooth poweredOn")
        default:
            print("Bluetooth Unknown")
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("\(#function) - \(#line): central = \(central) \nperipheral = \(peripheral) \nadvertisementData = \(advertisementData) \nRSSI = \(RSSI) \n ")
        if peripheral.name != nil {
            peripheral.accessibilityAssistiveTechnologyFocusedIdentifiers()
            self.peripherallist.append(peripheral)
            self.tableview.reloadData()
        }
        
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        self.curPeripheral = peripheral
        UserDefaults.standard.set(peripheral.identifier.uuidString, forKey: "curPeripheral")
        self.cenMG?.stopScan()
        peripheral.delegate = self as CBPeripheralDelegate
        peripheral.discoverServices(nil)
        self.textview.text = "\(peripheral)"
    }
    
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print("didFailToConnect peripheral: \(peripheral)")
    }
    
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        print("didDisconnectPeripheral: \(peripheral)")
        self.cenMG?.connect(peripheral, options: nil)
    }
    
    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        print("didDiscoverServices: \(String(describing: peripheral.services))")
        self.textview.text = self.textview.text + "\ndidDiscoverServices: \(String(describing: peripheral.services))"
        for service in peripheral.services! {
            peripheral.discoverCharacteristics(nil, for: service)
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        print("didDiscoverCharacteristicsFor service: \(service)")
        self.textview.text = self.textview.text + "\n\ndidDiscoverCharacteristicsFor service: \(service))"
        for characteristic in service.characteristics! {
            print("characteristic: \(characteristic)" + "\t uuid des: \(characteristic.uuid.description)")
            self.textview.text = self.textview.text + "\n\n<characteristic: UUID:\(characteristic.uuid.uuidString) value:\(characteristic.value) notifying:\(characteristic.isNotifying) properties:\(characteristic.properties) UUID:\(characteristic.uuid.description)>)"
            
            if characteristic.uuid.uuidString == "2A19" {
                peripheral.setNotifyValue(true, for: characteristic)
                print("uuid: \(characteristic.uuid.uuidString)")
                if characteristic.properties.contains(.read) {
                    peripheral.readValue(for: characteristic)
                    if let data = characteristic.value {
                        print("data: \(NSString.init(data: data, encoding: String.Encoding.utf8.rawValue)! as String)")
                        print("data int : \(data.first!)")
                        self.textview.text = self.textview.text + "\n\n\n\n\n\n 2A19 data: \(data.first!)"
                    }
                }
                
            }
            
            
            if characteristic.uuid.uuidString.hasPrefix("00001001-")  {
                peripheral.setNotifyValue(true, for: characteristic)
                print("uuid: \(characteristic.uuid.uuidString)")
                if characteristic.properties.contains(.read) {
                    peripheral.readValue(for: characteristic)
                    if let data = characteristic.value {
                        print("data: \(NSString.init(data: data, encoding: String.Encoding.utf8.rawValue)! as String)")
                        print("data int : \(data.first!)")
                        self.textview.text = self.textview.text + "\n\n\n\n\n\n sg data: \(data.first!)"
                    }
                }
            }
            
            
            
            if characteristic.uuid.uuidString.hasPrefix("00001005-") {
                peripheral.setNotifyValue(true, for: characteristic)
                print("uuid: \(characteristic.uuid.uuidString)")
                if characteristic.properties.contains(.read) {
                    peripheral.readValue(for: characteristic)
                    if let data = characteristic.value {
                        print("data: \(NSString.init(data: data, encoding: String.Encoding.utf8.rawValue)! as String)")
                        print("data int : \(data.first!)")
                        self.textview.text = self.textview.text + "\n\n\n\n\n\n vibrate data: \(data.first!)"
                    }
                }
            }
            
            
            
            
            
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        if characteristic.uuid.description == "Battery Level" {
            peripheral.readValue(for: characteristic)
            if let data = characteristic.value {
                
                print("data: \(NSString.init(data: data, encoding: String.Encoding.utf8.rawValue)! as String)")
                print("Update data int : \(data.first!)")
                
                os_log("Update data int : %@", log: .default, type: .error, "\(data.first!)")
                
                let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
                let file = path+"/log.txt"
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                let dateStr = dateFormatter.string(from: Date())
                try? dateStr.write(toFile: file, atomically: true, encoding: .utf8)
                DispatchQueue.main.async {
                    self.textview.text = self.textview.text + "\n\n\n\n\n\n 2A19 data: \(data.first!)"
                }
            }
        }
        
        
        if characteristic.uuid.uuidString.hasPrefix("00001001-")  {
            print("uuid: \(characteristic.uuid.uuidString)")
            if characteristic.properties.contains(.read) {
                peripheral.readValue(for: characteristic)
                if let data = characteristic.value {
                    print("sg data int : \(data.first!)")
                    self.textview.text = self.textview.text + "\n\n\n\n\n\n sg data: \(data.first!)"
                }
            }
        }
        
        
    }

    //MARK: - UITableViewDelegate && UITableViewDataSource
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return peripherallist.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellID")
        if cell == nil {
            cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "cellID")
        }
        
        cell!.textLabel?.text = peripherallist[indexPath.row].name ?? "null"
        cell!.detailTextLabel?.text = peripherallist[indexPath.row].identifier.uuidString
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let Peripheral = peripherallist[indexPath.row]
        self.cenMG?.connect(Peripheral, options: nil)
    }
    
}

